
package com.android.fitnesscenter.view.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.android.fitnesscenter.R;
import com.android.fitnesscenter.utils.ActivityHelper;
import com.android.fitnesscenter.utils.ConfigProperties;
import com.android.fitnesscenter.utils.Loger;
import com.android.fitnesscenter.utils.MapEntity;
import com.android.fitnesscenter.utils.TimerHelper;
import com.android.fitnesscenter.utils.ToastHelper;
import com.android.fitnesscenter.utils.ViewHelper;
import com.android.fitnesscenter.view.BaseActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

public class ServerBackupActivity extends BaseActivity {

    @ViewInject(R.id.txt_backup_list)
    private TextView txt_backup_list;

    @ViewInject(R.id.txt_more)
    private TextView txt_more;

    @ViewInject(R.id.btn_ok)
    private Button btn_ok;

    private ArrayList<MapEntity> mMapEntityList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.server_backup_layout);
        ViewUtils.inject(this);
        initTitleBar(getString(R.string.txt_backup));
        queryBackHis();
    }

    private PopupWindow mPopupWindow;

    protected void showPopWindows() {
        if (mPopupWindow != null) {
            mPopupWindow.dismiss();
            mPopupWindow = null;
        }
        if (mPopupWindow == null) {
            createPopupWindow();
        }
        mPopupWindow.showAsDropDown(txt_more);
    }

    private void createPopupWindow() {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View popupWindow = layoutInflater.inflate(R.layout.query_detail_popwindows_layout, null);
        ListView list_view = (ListView) popupWindow.findViewById(R.id.list_view);
        SimpleAdapter adapter = new SimpleAdapter(this, getDataByType(),
                R.layout.query_detail_popwindows_list_item, new String[] {
                        "title"
                },
                new int[] {
                        R.id.txt_title
                });
        list_view.setAdapter(adapter);
        int screenWidth = ActivityHelper.getScreenWidth(this);
        mPopupWindow = new PopupWindow(popupWindow, screenWidth, LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(true); // 设置PopupWindow可获得焦点
        mPopupWindow.setTouchable(true); // 设置PopupWindow可触摸
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new PaintDrawable());
    }

    private List<HashMap<String, String>> getDataByType() {
        int length = mMapEntityList.size();
        List<HashMap<String, String>> title_list = new ArrayList<HashMap<String, String>>();
        for (int i = 0; i < length; i++) {
            MapEntity entity = mMapEntityList.get(i);
            HashMap<String, String> map_title = new HashMap<String, String>();
            map_title.put(
                    "title",
                    TimerHelper.formatTime(entity.getString(BackUpResult.CREATE_TIME)) + " "
                            + entity.getString(BackUpResult.NAME));
            title_list.add(map_title);
        }
        return title_list;
    }

    private void queryBackHis() {
        RequestParams params = new RequestParams();
        HttpUtils http = new HttpUtils();
        String imei = getIMEI();
        params.addBodyParameter("token", getToken());
        params.addBodyParameter("imei", imei);
        String url = ConfigProperties.SERVICE_URL + "queryBackHis.do";
        Loger.e("url is " + url + " params is " + params);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                if (mDialog == null) {
                    mDialog = new ProgressDialog(ServerBackupActivity.this);
                }
                mDialog.setCanceledOnTouchOutside(false);
                mDialog.setMessage("加载中,请等待...");
                mDialog.show();
                if (mMapEntityList == null) {
                    mMapEntityList = new ArrayList<MapEntity>();
                } else {
                    mMapEntityList.clear();
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                if (ServerBackupActivity.this != null && !ServerBackupActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    if (stringResponseInfo != null && !TextUtils.isEmpty(stringResponseInfo.result)) {
                        Loger.e("stringResponseInfo.result is " + stringResponseInfo.result);
                        try {
                            JSONObject jsonObject = new JSONObject(stringResponseInfo.result);
                            if (jsonObject != null) {
                                boolean success = jsonObject.getBoolean("success");
                                if (success) {
                                    JSONArray jsonArray = jsonObject.getJSONArray("list");
                                    int length = jsonArray.length();
                                    for (int i = 0; i < length; i++) {
                                        MapEntity entity = new MapEntity();
                                        JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                                        String createTime = jsonObject2.getString(BackUpResult.CREATE_TIME_STR);
                                        entity.setValue(BackUpResult.CREATE_TIME, createTime);
                                        String id = jsonObject2.getString(BackUpResult.ID_STR);
                                        entity.setValue(BackUpResult.ID, id);
                                        String name = jsonObject2.getString(BackUpResult.NAME_STR);
                                        entity.setValue(BackUpResult.NAME, name);
                                        String username = jsonObject2.getString(BackUpResult.USER_NAME_STR);
                                        entity.setValue(BackUpResult.USER_NAME, username);
                                        mMapEntityList.add(entity);
                                    }
                                    if (mMapEntityList != null && mMapEntityList.size() > 0) {
                                        MapEntity curEntity = mMapEntityList.get(0);
                                        String info = TimerHelper.formatTime(curEntity
                                                .getString(BackUpResult.CREATE_TIME))
                                                + " " + curEntity.getString(BackUpResult.NAME);
                                        txt_backup_list.setText(String.format(getString(R.string.txt_backup_list_str),
                                                info));
                                    } else {
                                        txt_backup_list.setText(String.format(getString(R.string.txt_backup_list_str),
                                                "暂无备份记录"));
                                    }
                                } else {
                                    String msg = jsonObject.getString("message");
                                    new ViewHelper(ServerBackupActivity.this).showBTNDialog(msg);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        new ViewHelper(ServerBackupActivity.this).showBTNDialog("加载失败,请重试!");
                    }
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Loger.e("msg:" + msg);
                if (ServerBackupActivity.this != null && !ServerBackupActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    new ViewHelper(ServerBackupActivity.this).showErrorDialog(error);
                }
            }
        });

    }

    public interface BackUpResult {
        public static final String CREATE_TIME_STR = "createTime";
        public static final String ID_STR = "id";
        public static final String NAME_STR = "name";
        public static final String USER_NAME_STR = "username";

        public static final int CREATE_TIME = 0;
        public static final int ID = 1;
        public static final int NAME = 2;
        public static final int USER_NAME = 3;

    }

    private void backUpDb() {
        RequestParams params = new RequestParams();
        HttpUtils http = new HttpUtils();
        String imei = getIMEI();
        params.addBodyParameter("token", getToken());
        params.addBodyParameter("imei", imei);
        String url = ConfigProperties.SERVICE_URL + "backUpDb.do";
        Loger.e("url is " + url + " params is " + params);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                if (mDialog == null) {
                    mDialog = new ProgressDialog(ServerBackupActivity.this);
                }
                mDialog.setCanceledOnTouchOutside(false);
                mDialog.setMessage("加载中,请等待...");
                mDialog.show();
            }

            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                if (ServerBackupActivity.this != null && !ServerBackupActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    if (stringResponseInfo != null && !TextUtils.isEmpty(stringResponseInfo.result)) {
                        Loger.e("stringResponseInfo.result is " + stringResponseInfo.result);
                        try {
                            JSONObject jsonObject = new JSONObject(stringResponseInfo.result);
                            if (jsonObject != null) {
                                String msg = jsonObject.getString("message");
                                boolean success = jsonObject.getBoolean("success");
                                if (success) {
                                    ToastHelper.getInstance().showShortMsg(msg);
                                    queryBackHis();
                                } else {
                                    new ViewHelper(ServerBackupActivity.this).showBTNDialog(msg);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        new ViewHelper(ServerBackupActivity.this).showBTNDialog("加载失败,请重试!");
                    }
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Loger.e("msg:" + msg);
                if (ServerBackupActivity.this != null && !ServerBackupActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    new ViewHelper(ServerBackupActivity.this).showErrorDialog(error);
                }
            }
        });

    }

    @OnClick(R.id.txt_more)
    public void txt_more(View view) {
        if (mMapEntityList != null && mMapEntityList.size() > 0) {
            showPopWindows();
        }
    }

    @OnClick(R.id.btn_ok)
    public void btn_ok(View view) {
        backUpDb();
    }

    @Override
    protected void titlebarMethod(int id) {

    }

}
